package com.lzy.permission.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.lzy.permission.entity.Resource;
import com.lzy.permission.entity.Role;
import com.lzy.permission.entity.User;

/**
 * UserDetails hibernate实现
 * 
 * @author pwz
 *
 */
public class UserDetailsHibernateImpl implements UserDetails{
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * hiberante user
	 */
	private User user ;
	
	public UserDetailsHibernateImpl() {
	}
	
	public UserDetailsHibernateImpl(User user) {
		this.user = user;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * 获取授权信息
	 */
	public Collection<GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		Set<Role> roles = this.user.getUserRoles();
		GrantedAuthorityImpl authorityImpl = null;
		for (Role role : roles) {
			for (Resource resource : role.getResources()) {
				authorityImpl = new GrantedAuthorityImpl(resource.getName());
				if(authorities == null || !authorities.contains(authorityImpl)){
					authorities.add(authorityImpl);
				}
			}
		}
		return authorities;
	}

	public String getPassword() {
		return user.getPassword();
	}

	public String getUsername() {
		return user.getUsername();
	}

	public boolean isAccountNonExpired() {
		return true;
	}

	public boolean isAccountNonLocked() {
		return true;
	}

	public boolean isCredentialsNonExpired() {
		return true;
	}

	public boolean isEnabled() {
		return true;
	}
}
